import axios from "axios";
import { Message, MessageBox } from "element-ui";
import md5 from "js-md5";
import config from "../../config";
// 判断是否是开发环境
const isDev = process.env.NODE_ENV === "development";


// 创建axios实例
const service = axios.create({
  baseURL: config.baseURL || "", // api的base_url
  timeout: 5000, // 请求超时时间
});

const timestamp = Date.now();
// 生成8-10位随机字符串
const generateNonce = () => {
  const chars =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const length = Math.floor(Math.random() * 3) + 8; // 8-10位随机长度
  let result = "";
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};
const nonce = generateNonce();
// request拦截器
service.interceptors.request.use(
  (config) => {
    if (localStorage.getItem("token")) {
      // config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token')
      config.headers.token = `${localStorage.getItem("token")}`;
    }
    config.headers.signature = md5(
      "timestamp=" +
        timestamp +
        "&nonce=" +
        nonce +
        "&01e553a3697a0479bac95466cea61487e1dba680"
    ).toString();
    config.headers.timestamp = timestamp;
    config.headers.nonce = nonce;

    return config;
  },
  (error) => {
    console.log(error); // for debug
    Promise.reject(error);
  }
);
// respone拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code === 200) {
      return res.data;
    }
    // 假设正常状态码为20000，根据你的实际业务调整
    if (res.code !== 200) {
      Message({
        message: res.msg || "操作失败",
        type: "error",
        duration: 5 * 1000,
      });

      // 特殊token处理
      if ([402].includes(res.code)) {
        return handleTokenExpired();
      }

      return Promise.reject(res.msg || "Error");
    }
  },
  (error) => {
    console.log("请求错误:", error);
    if (error.response) {
      // 有响应但状态码不在2xx范围内
      handleHttpError(error.response);
    } else if (error.request) {
      // 请求已发出但没有收到响应
      handleNetworkError(error);
    } else {
      // 发送请求时出了些问题
      handleRequestError(error);
    }
    return Promise.reject(error);
  }
);

/**
 * 处理请求错误
 * @param {Object} error 错误对象
 */
function handleRequestError(error) {
  Message({
    message: error.msg || "请求出错",
    type: "error",
    duration: 5 * 1000,
  });
}

/**
 * 处理网络错误
 * @param {Object} error 错误对象
 */
function handleNetworkError(error) {
  Message({
    message: "网络异常，请检查网络连接",
    type: "error",
    duration: 5 * 1000,
  });
  // 可以在这里添加网络错误上报
  //logNetworkError(error);
}
/**
 * 处理HTTP状态码错误
 * @param {Object} response 错误响应对象
 */
function handleHttpError(response) {
  const status = response.status;
  const data = response.data;
  console.log(status, "1111111data");

  let errorMessage = "请求错误";

  switch (status) {
    case 400:
      errorMessage = data.msg || "请求参数错误";
      break;
    case 401:
      errorMessage = "未授权，请登录";
      // // 清除token等操作
      // localStorage.removeItem("token");
      // // 跳转到登录页
      // window.location.href = "/login";
      break;
    case 402:
      errorMessage = "请先登录";
      // 跳转到登录页
      handleTokenExpired();
      break;
    case 403:
      errorMessage = "拒绝访问";
      break;
    case 404:
      errorMessage = `请求地址不存在: ${response.config.url}`;
      break;
    case 405:
      errorMessage = "请求方法不被允许";
      break;
    case 408:
      errorMessage = "请求超时";
      break;
    case 500:
      errorMessage = data.msg || "服务器内部错误";
      // 可以在这里添加自动上报错误的逻辑
      break;
    case 502:
      errorMessage = "网关错误";
      break;
    case 503:
      errorMessage = "服务不可用";
      break;
    case 504:
      errorMessage = "网关超时";
      break;
    default:
      errorMessage = `未知错误 (${status})`;
  }

  Message({
    message: errorMessage,
    type: "error",
    duration: 5 * 1000,
  });
}

// Token过期处理函数
function handleTokenExpired() {
  return MessageBox.confirm("登录状态已过期，请重新登录", "系统提示", {
    confirmButtonText: "重新登录",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 清除token等操作
      localStorage.removeItem("token");
      // 跳转到登录页
      window.location.href = "/login";
      return Promise.reject("Token expired");
    })
    .catch(() => {
      return Promise.reject("用户取消操作");
    });
}

// 未授权处理函数
function handleUnauthorized() {
  localStorage.removeItem("token");
  // 可以根据路由跳转到登录页
  if (window.location.pathname !== "/login") {
    window.location.href = `/login?redirect=${encodeURIComponent(
      window.location.pathname
    )}`;
  }
  return Promise.reject("Unauthorized");
}

export default service;
